#coding:utf-8
from models import Files, Categories
from google.appengine.api import memcache
from google.appengine.api import images
from google.appengine.api import users

def addFile( name, mime, bf):
    'Add File'
    file = Files(name=name, mime=mime, bf=bf, size=len(bf))
    if mime.find("image") != -1:
        file.isimage = 1
    else:
        file.isimage = 0
    file.put()
    return file

def delFileByid(id):
    file = Files.get_by_id(int(id))
    msg = ""
    if not file:
        msg = "There is no file with id='%s'!" %(id)
    else:
        msg = "File '%s' has been deleted!" %(file.name)
        file.delete()
    return msg

def getFileByID(id):
    id=int(id)
    return Files.get_by_id(id)
    
# it will return maximum 25 files, but only 24 files will be displayed
# the last one is used for paging
def getAllFiles(index=0):
    return Files.all().order('-created_at').fetch(25,index*24)

def getPageing(index, page=0):
    s="/list/%s"
    if page==0:
        if index==25:
            return (None,"/list/1")
        else:
            return (None,None)
    if index==25:
        return ("/list/",s%(page+1)) if page==1 else (s%(page-1),s%(page+1))
    return ("/list/",None) if page==1 else (s%(page-1),None)


def getUserGreeting(url):
    user = users.get_current_user()
    greeting = ""
    if user:
        greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
        (user.nickname(), users.create_logout_url(url)))
    else:
            # this should be impossible, since login=admin
        greeting = ("<a href=\"%s\">Sign In</a>" %
        users.create_login_url(url))
    return greeting
